package com.fuang.io.nio2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * nio2 服务类绑定和监听处理类
 * 1，AsynchronousServerSocketChannel绑定监听端口
 * 2，AsynchronousServerSocketChannel用accept方法处理接入请求由AcceptCompletionHandler处理接入
 * 3，接入请求成功后由ReadCompletionHandler处理异步read -> handle -> 异步写入
 * Created by Fuang on 2018-9-19.
 */
public class AsyncTimeServerHandler implements Runnable {

    CountDownLatch latch; // 阻塞当前线程，防止线程直接运行结束，等
    AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AsyncTimeServerHandler(int port) {
        try {
            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
            System.out.println("The time server is start in port : " + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        latch = new CountDownLatch(1);

        asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
